package com.efeichong.project.domain.entity.db;

import com.efeichong.audit.InsertDefault;
import com.efeichong.audit.UpdateDefault;
import com.efeichong.common.config.AuditorHolder;
import com.efeichong.common.domain.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @author
 * @date 2020/12/03
 * @description 部门表
 */
@Setter
@Getter
@Entity
@Table(indexes = {
        @Index(name = "PRIMARY", columnList = "id", unique = true)
})
@DynamicInsert
@DynamicUpdate
public class SysDept extends BaseEntity {
    @Column(name = "[name]", columnDefinition = "varchar(30) not null comment'名字'")
    private String name;
    /**
     * 显示顺序
     */
    @Column(name = "[sort]", columnDefinition = "int default'0' comment'显示顺序'")
    private Integer sort;

    /**
     * 联系电话
     */
    @Column(name = "[phone]", columnDefinition = "varchar(11) comment'联系电话'")
    private String phone;

    /**
     * 邮箱
     */
    @Column(name = "[email]", columnDefinition = "varchar(50) comment'邮箱'")
    private String email;

    /**
     * 创建者
     */
    @InsertDefault(val = AuditorHolder.class)
    @JoinColumn(name = "[create_by]")
    @ManyToOne(fetch = FetchType.LAZY)
    private SysUser createBy;

    /**
     * 更新者
     */
    @UpdateDefault(val = AuditorHolder.class)
    @JoinColumn(name = "[update_by]")
    @ManyToOne(fetch = FetchType.LAZY)
    private SysUser updateBy;

    /**
     * 部门负责人
     */
    @JoinTable(name = "sys_dept_leader_ship",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "dept_id", referencedColumnName = "id"))
    @ManyToMany(fetch = FetchType.LAZY)
    private List<SysUser> leaders;

    /**
     * 部门用户
     */
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "sysDepts")
    private Set<SysUser> sysUsers;

    /**
     * 部门上级
     */
    @ManyToOne(fetch = FetchType.EAGER)
    private SysDept parent;

    /**
     * 部门下级
     */
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
    private List<SysDept> children;

    /**
     * 所有父级
     */
    @JoinTable(name = "sys_dept_dept_ship",
            joinColumns = @JoinColumn(name = "id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "parent_id", referencedColumnName = "id"))
    @ManyToMany(fetch = FetchType.LAZY)
    private List<SysDept> deptParents = new ArrayList<>();

    /**
     * 所有子集
     */
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "deptParents")
    private List<SysDept> deptChildren;
}
